/**
 * @author Created by qiush on 2017-07-12.
 */

const {BrowserWindow} = require('electron');

const path = require('path');
const url = require('url');

function _getStartUrl(pageUrl) {
  if (process.env.ELECTRON_START_URL) {
    return `${process.env.ELECTRON_START_URL}/${pageUrl}`;
  }
  return url.format({
    pathname: path.join(__dirname, `../../../build/${pageUrl}`),
    protocol: 'file:',
    slashes: true
  });
}

function _tryOpenDevTool(win) {
  if (process.env.ELECTRON_START_URL) {
    win.webContents.openDevTools();
  }
}

const defaultOptions = {
  webPreferences: {
    experimentalFeatures: true
  }
};

const windowUtil = {
  createModalWindow(parent, pageUrl, width, height) {
    // Create the browser window.
    const win = new BrowserWindow(Object.assign(defaultOptions, {
      width,
      height,
      parent,
      modal: true,
      center: true,
    }));

    // and load the index.html of the app.
    const startUrl = _getStartUrl(pageUrl);
    win.loadURL(startUrl);

    // Open the DevTools.
    _tryOpenDevTool(win);

    return win;
  },

  createWindow(pageUrl, width, height) {
    // Create the browser window.
    const win = new BrowserWindow(Object.assign(defaultOptions, {
      width,
      height,
    }));

    // and load the index.html of the app.
    const startUrl = _getStartUrl(pageUrl);
    win.loadURL(startUrl);

    // Open the DevTools.
    _tryOpenDevTool(win);

    return win;
  }
};

module.exports = windowUtil;
